import axios from 'axios'
import Vue from 'vue'
import { errorAlert } from '../utils/alert';
import store from '../store/index';
import router from '../router/index';

if (process.env.NODE_ENV === 'development') {
    Vue.prototype.$pre = "http://localhost:2000"
} else {
    // 生产环境
    Vue.prototype.$pre = ""
}

//请求拦截
axios.interceptors.request.use(config => {
    if(config.url != '/api/userlogin'){
        config.headers.authorization = store.getters.userInfo.token;
    }
    return config;
})

//响应拦截
axios.interceptors.response.use(res => {
    if (res.data.code != 200) {
        errorAlert(res.data.msg);
    }
    if( res.data.msg == '登录已过期或访问权限受限'){
        store.dispatch('chageUserInfo',{});
        router.push('/login');
    }
    return res;
})


//get请求
export const get = (url, params = {}) => {
    return axios({
        url,
        method: 'get',
        params,
    })
}

//post请求
export const post = (url, params, haveFile = false) => {
    let data = null;
    if (haveFile) {
        data = new FormData();
        for (let k in params) {
            data.append(k, params[k])
        }
    } else {
        data = params;
    }

    return axios({
        url,
        method: 'post',
        data,
    })
}
